import axios from "axios";

const CancelToken = axios.CancelToken;

const CLEAR_CACHE_INTERVAL = 60 * 1000;
const EXPIRED_TIME = 5 * 100;
const MAX_CACHE_NUMBER = 50;

// 要进行缓存的url的列表
export const cacheList = ["/product/id/"];

// 接口数据缓存的map对象，请求的url和params作为key 响应数据作为value
const ApiCache = new Map();

const expires = new Map();

// 设置缓存过期时间
export function setExpires(key) {
  expires.set(key, Date.now() + EXPIRED_TIME);
}

// 设置缓存数据
export function setApiCache(url, data, params = {}) {
  if (!cacheList.includes(url)) return;
  const key = url + JSON.stringify(params);
  console.log(key + " :新设置缓存");
  ApiCache.set(key, data);
  setExpires(key);

  outRangeCache();
}

// 判断缓存中是否有对应的key
export function hasApiCache(url, params = {}) {
  const key = url + JSON.stringify(params);
  if (!ApiCache.has(key)) return false;
  // 检查 对应的缓存数据有没有过期
  if (expires.get(key) <= Date.now()) {
    console.log(key + " ：缓存已经过期！");
    deleteApiCache(key);
    return false;
  }

  return true;
}

// 根据key获取缓存结果
export function getApiCache(url, params = {}) {
  const key = url + JSON.stringify(params);
  setExpires(key);
  return ApiCache.get(key);
}

export function deleteApiCache(key) {
  ApiCache.delete(key);
  expires.delete(key);
}

export function clearCache() {
  for (let [key, timestamp] of expires) {
    if (timestamp <= Date.now()) {
      deleteApiCache(key);
    }
  }
}

export function outRangeCache() {
  const number = expires.size - MAX_CACHE_NUMBER;
  if (number > 0) {
    console.log("超出缓存数量");
    [...expires.entries()]
      .sort((a, b) => a[1] - b[1])
      .slice(0, number)
      .forEach(([key]) => deleteApiCache(key));
  }
}

// 请求config中加入cancelToken配置， 并且获取取消函数
export function addCancelConfig(url, config) {
  if (!cacheList.includes(url)) return;

  let cancel = null;
  config.cancelToken = new CancelToken((c) => (cancel = c));

  return cancel;
}
